package remote;

import java.io.IOException;
import java.io.Serializable;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;

public class SerializableIterator<E extends Serializable> implements Iterator<E>, Serializable{

	private static final long serialVersionUID = -7150379563009282645L;
	
	/** Keeps actual collection*/
	private transient Collection<E> actualCollection;
	
	private transient Iterator<E> actualIter;
	
	public SerializableIterator (Collection<E> collection){
		actualCollection = collection;
		actualIter = actualCollection.iterator();
	}

	
	public boolean hasNext() {
		return actualIter.hasNext();
	}

	
	public E next() {
		return actualIter.next();
	}

	
	public void remove() {
		throw new UnsupportedOperationException("Operator is read-only");
	}
	
	private void writeObject(java.io.ObjectOutputStream out) throws IOException{
		
		out.writeInt(actualCollection.size());
		Iterator<E> writeIter =  actualCollection.iterator();
		
		while (writeIter.hasNext()){
			out.writeObject(writeIter.next());
		}
	}
	
	private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException{
		
		int size = in.readInt();
		actualCollection = new LinkedList<E>();
		
		for (int readCtr = 0; readCtr < size; readCtr++){
			actualCollection.add((E)in.readObject());
		}
		
		actualIter = actualCollection.iterator();
	}
	

	

}
